import http from '@/utils/http'
import OSS from 'ali-oss'
import responseDataType from 'responseDataType'
import { userModule } from '@/store/modules/user'
import { ElMessage } from 'element-plus'
export interface OSSBasePath {
  contact: string
  docFile: string
  help: string
  homeworkTemplate: string
  homeworkTodo: string
  operationNotice: string
  returnVisit: string
}
export interface OSSConfig {
  accessKeyId: string
  accessKeySecret: string
  basePath: OSSBasePath
  bucket: string
  domain: string
  endpoint: 'oss-cn-beijing.aliyuncs.com'
  expiration: string
  securityToken: string
  msg: string
  requestId: string
}
interface Opt {
  change?: Fn<string, void>
  progress?: (px: number, checkpoint: any) => void
}

export type UrlItem = {
  url: string
  poster: string
}
// 获取oss 配置
const getOssToken = () => http<responseDataType.IData<OSSConfig>>({
  url: 'xxx',
  method: 'post'
})
// 获取 OSS 配置
async function getOSSConf() {
  const { data } = await getOssToken()
  let optins = {
    accessKeyId: data.accessKeyId,
    accessKeySecret: data.accessKeySecret,
    bucket: data.bucket,
    endpoint: data.endpoint,
    region: 'oss-cn-beijing.aliyuncs.com',
    stsToken: data.securityToken,
    timeout: 600 * 1000
  }
  return {
    optins,
    OSSBasePath: data.basePath
  }
}
// 开始上传
export function useOss() {
  let optins: Nullable<OSS.Options> = null
  let basePath: Nullable<OSSBasePath> = null
  if (!optins || !basePath) {
    getOSSConf()
      .then(resData => {
        optins = resData.optins
        basePath = resData.OSSBasePath
      })
  }
  // 获取文件基础路径
  function getFileBasePath() {
    const tempPath = basePath?.homeworkTodo as string
    const now = new Date()
    const year = now.getFullYear()
    const month = now.getMonth() + 1 < 10 ? '0' + (now.getMonth() + 1) : now.getMonth() + 1
    const day = now.getDate() < 10 ? '0' + now.getDate() : now.getDate()
    let path = tempPath.replace(/studentId/, userModule.userInfo.uid || '')
    path = path.replace(/yyyyMMdd/, `${year}${month}${day}`)
    return path
  }
  // 上传文件到 OSS
  function upload(fileName: string, file: File, opt?: Opt) {
    if (optins) {
      /* eslint-disable-next-line */
      const oss = new OSS(optins)
      oss.multipartUpload(fileName, file, {
        parallel: 50,
        progress: (p, checkpoint) => {
          opt?.progress?.(p, checkpoint)
        },
        timeout: 60000,
        mime: 'video/mp4'
      })
        .then((res: any) => {
          let url = res.res.requestUrls[0].split('?')[0]
          opt?.change?.(url)
        })
        .catch(err => {
          ElMessage({
            message: err || '上传失败',
            type: 'error'
          })
        })
    } else {
      ElMessage({
        message: 'OSS 参数获取失败，请重试',
        type: 'error'
      })
    }
  }
  return {
    // 设置参数
    uploadFile: (files: FileList, opt?: Opt) => {
      const target = files[0]
      const name = target.name
      // 获取文件扩展名
      const extname = name.substring(name.lastIndexOf('.') + 1)
      const random = new Date().getTime() * Math.floor(Math.random() * 100)
      const fileName = `${getFileBasePath()}${random}.${extname}`
      upload(fileName, target, opt)
    }
  }
}
